#!usr/bin/env python
#Removes noisy columns from fasta file given as input. Output is the path to the new file.
from Bio import SeqIO
from Bio.Seq import Seq
import sys
import os
import re
import string

def check_column(column):
	'''Check if column is noisy, column is an list'''
	uniq=0
	not_uniq_list=[] #List of chars in column that is not unique
	for char_i in range(len(column)):
		if column[char_i]=='-': #Check for indel
			return(True)
		else:
			list_check=False
			for char in not_uniq_list: #Check if its in not_uniq_list
				if column[char_i]==char:
					list_check=True
					break
			if not list_check:
				for i in range(char_i+1,len(column)): #Check if its in the rest of column
					if column[char_i]==column[i]:
						not_uniq_list.append(column[char_i])
						break
				else:
					uniq+=1
	if uniq>0.5*len(column):
		return(True)
	else:
		return(False)				

def remove_columns(all_seq):
	'''Removes noise columns in all_seq'''
	all_seq_remove=[]
	for i in range(len(all_seq)): #Build list of lists
		all_seq_remove.append([])
	for column in range(len(all_seq[0])):
		column_list=[]
		for row in range(len(all_seq)): #Get column
			column_list.append(all_seq[row][column])
		if not check_column(column_list): #Check column
			i=0
			for char in column_list: #Add column to list of lists
				all_seq_remove[i].append(char)
				i+=1
	return(all_seq_remove)
	
def split_fasta(line):
	'''Takes a string and inserts an end of line characther at after each 60 charachters'''
	line2=''
	while(len(line)>60):
		line2=line2+line[0:60]
		line2=line2+'\n'
		line=line[60:]
	line2=line2+line
	return(line2)

def get_seq_names(file_name):
	'''Gets all seq and names from a fasta file'''
	handle = open(file_name, "rU")
	all_seq=[]
	names_seq=[]
	for record in SeqIO.parse(handle, "fasta"):
    		all_seq.append(record.seq)
		names_seq.append(record.id)
	handle.close()
	return(all_seq,names_seq)

def main(file_name):
	'''Main part'''
	all_seq, names_seq=get_seq_names(file_name) #Read file
	all_seq_new=remove_columns(all_seq); #Remove noisy columns
	name=file_name.rpartition('.')[0] #Remove .msl from filename
	path_new=name+'.removed.msl'
	#Print to file
	handle=open(path_new,'w')
	for i in range(len(all_seq)):
		handle.write('>'+names_seq[i]+'\n')
		handle.write(split_fasta(''.join(all_seq_new[i]))+'\n')
	handle.close()
	return(path_new)

